package com.daxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultUtil;
import com.daxt.common.util.EkpHttpWsUtil;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.mapper.sys.*;
import com.daxt.mapper.use.ActRuTaskMapper;
import com.daxt.mapper.use.UseBorrowRecordMapper;
import com.daxt.model.dic.VersionsMarkType;
import com.daxt.model.service.archives.vo.ArchivesClass;
import com.daxt.model.service.archives.vo.ArchivesDoc;
import com.daxt.model.service.archives.vo.ArchivesType;
import com.daxt.model.service.base.vo.*;
import com.daxt.model.service.use.vo.ActRuTask;
import com.daxt.model.service.use.vo.UseBorrowRecord;
import com.daxt.service.*;
import com.daxt.utils.ArchivesUtil;
import com.daxt.utils.BaseUtil;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class UseBorrowServiceImpl implements UseBorrowService {

    private static final Log log = LogFactory.getLog(ArchivesService.class);

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    IdentityService identityService;
    @Autowired
    UseBorrowRecordMapper useBorrowRecordMapper;
    @Autowired
    private UserDeptMapper userDeptMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private ArchivesDocMapper archivesDocMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private BaseTaskMapper baseTaskMapper;
    @Autowired
    private ActRuTaskMapper actRuTaskMapper;
    @Autowired
    private ArchivesClassMapper archivesClassMapper;
    @Autowired
    private ArchivesTypeMapper archivesTypeMapper;

    @Autowired
    private ArchivesAcceptService acceptService;



    @Override
    public Result<String> startBorrow(UseBorrowRecord borrowApply) {
        List<UserDept> userDeptList =  userDeptMapper.selectList(new QueryWrapper<UserDept>().eq("userId",borrowApply.getUserId()));
        List<Long> deptIds = new ArrayList();
        userDeptList.forEach((UserDept ud)->{
            deptIds.add(ud.getDeptId());
        });


        //部门领导
        Map<String, Object> variables = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<>();
        param.put("postCode","deptLeader");
        param.put("deptIds",deptIds);
//        param.put("userId",loginUser.getId());

        List<BaseUser> userList = userService.gainDeptPostUser(param);
        if(!BaseUtil.listIsNotNullElement(userList)){
            return ResultUtil.error("没有找到部门领导对应的审核人");
        }
        variables.put("deptLeader", userList.get(0).getUsername());




//        //获取公司下的所有部门ID
//        List<Long> deptIds2 = new ArrayList();
//        Dept dept = deptMapper.selectById(userDeptList.get(0).getDeptId());
//        String p = dept.getPids().substring(dept.getPids().indexOf("/") + 1);
//        String companyCode = p.substring(0,p.indexOf("/"));
//
//        List<Dept> deptList = deptMapper.selectList(new QueryWrapper<Dept>().like("pids",companyCode));
//        deptList.forEach((Dept d)->{
//            deptIds2.add(d.getId());
//        });
//
//
//        //办公室主任
//        Map<String, Object> param2 = new HashMap<>();
//        param2.put("postCode","officeLeader");
//        param2.put("deptIds",deptIds2);
//        List<BaseUser> userList2 = userService.gainDeptPostUser(param2);
//        if(!BaseUtil.listIsNotNullElement(userList2)){
//            return ResultUtil.error("没有找到办公室主任对应的审核人");
//        }
//        variables.put("officeLeader", userList2.get(0).getUsername());
//
//
//        //档案管理员
//        Map<String, Object> param3 = new HashMap<>();
//        param3.put("postCode","archivistLeader");
//        param3.put("deptIds",deptIds2);
//        List<BaseUser> userList3 = userService.gainDeptPostUser(param3);
//        if(!BaseUtil.listIsNotNullElement(userList3)){
//            return ResultUtil.error("没有找到档案管理员对应的审核人");
//        }
//        variables.put("archivistLeader", userList3.get(0).getUsername());

        String businesskey=String.valueOf(borrowApply.getId());//使用Borrowapply表的主键作为businesskey,连接业务数据和流程数据
        identityService.setAuthenticatedUserId(borrowApply.getUserId() + "");
        ProcessInstance instance = runtimeService.startProcessInstanceByKey("borrow",businesskey,variables);
        String instanceid = instance.getId();
        borrowApply.setProcessId(instanceid);
        useBorrowRecordMapper.updateById(borrowApply);

        //待办
        BaseTask bt = EkpHttpWsUtil.borrowEkp(instanceid,userList.get(0).getUsername(),borrowApply.getId());
        if (null != bt) baseTaskMapper.insert(bt);

        if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
            //流程接入-流程分析平台-发起流程
            long deptId=userDeptList.get(0).getDeptId();
            List<Dept> deptList = deptMapper.getAllParentDept(deptId);
            String categoryId=deptList.get(1).getDeptCode();
            String categoryName=deptList.get(1).getDeptName();
            String orgId=deptList.get(deptList.size()-1).getDeptCode();
            String orgName=deptList.get(deptList.size()-1).getDeptName();
            acceptService.sendFlow(instanceid,categoryId,categoryName,borrowApply.getCreateBy(),borrowApply.getCreateTime(),"档案借阅",orgId,orgName);
        }


        return ResultUtil.success();
    }

    @Override
    public void buildArchives(List<UseBorrowRecord> list) {
        list.forEach((UseBorrowRecord ubr) -> {

            //增加档案基础信息
            ArchivesDoc ad = archivesDocMapper.selectById(ubr.getFileId());
            if(null != ad){
                ArchivesType archivesType = archivesTypeMapper.selectById(ad.getTypeId());
                ArchivesClass archivesClass = archivesClassMapper.selectById(ad.getClassId());
                ubr.setBaseDocDto(ArchivesUtil.buildBaseDoc(ad));
                ubr.setTypeNum(archivesType.getTypeNum());
                if(archivesClass!=null){
                    ubr.setClassTreeStr(archivesClass.getTreeStr());
                }

            }
            String deptName = userService.gainDeptNameByUserId(ubr.getUserId().toString());

            ubr.setDeptName(deptName);
            QueryWrapper<ActRuTask> actRuTaskQueryWrapper=new QueryWrapper<>();
            actRuTaskQueryWrapper.eq("PROC_INST_ID_",ubr.getProcessId());
            ActRuTask actRuTask= actRuTaskMapper.selectOne(actRuTaskQueryWrapper);
            if(actRuTask!=null){
                ubr.setUpdateBy(actRuTask.getAssignee());
            }
        });
    }

    @Override
    public int borrowNumByAuthTypeAndDocId(String authType, Long docId) {
        QueryWrapper<UseBorrowRecord> ubaQw = new QueryWrapper<UseBorrowRecord>();
        ubaQw.eq("authType",authType);
        ubaQw.eq("fileId",docId);
        ubaQw.and(Wrapper -> Wrapper.eq("state", "0").or().eq("state", "2"));
        int i = useBorrowRecordMapper.selectCount(ubaQw);
        return i;
    }


}
